package cn.qyd.threadpool;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author 邱运铎
 * 并行计算一般都是CPU处理，不怎么实际io操作，所以认为是CPU密集型任务，线程核心数为 CPU核心数 + 1
 * @date 2024-03-23 0:52
 */
public class ParallelCalculationUpgrade {
    private final static int CPU_CORE_COUNT = Runtime.getRuntime().availableProcessors();
    private final static int CORE_POOL_SIZE = CPU_CORE_COUNT + 1;
    private final static int MAX_POOL_SIZE = CPU_CORE_COUNT * 2;

    private static ExecutorService executor = new ThreadPoolExecutor(CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            10L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000));

    public static void main(String[] args) {
        Callable<Double> task = () -> Math.random()*100;

        List<Future<Double>> results = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            results.add(executor.submit(task));
        }

        for (Future<Double> future : results) {
            try {
                System.out.println(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        executor.shutdown();
    }
}
